import java.io.StringReader;

import javax.ws.rs.core.MultivaluedMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class OneBusAwayTest {
	public static void main(String[] args) {
		Client client = Client.create();
		WebResource webResource = client
				.resource("http://api.onebusaway.org/api");
		MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
		queryParams.add("key", "e5cceffb-3a4d-4f95-96e6-42fb93d3b792");
		String response = webResource.path("where/stop/1_75403.xml")
				.queryParams(queryParams).get(String.class);
		System.out.println(response);

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document doc = null;
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(response));
			doc = db.parse(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// get data for all routes
		NodeList l = doc.getElementsByTagName("route");
		
		// select out the name of each route
		for(int i = 0; i < l.getLength(); i++) {
			Element elmt = (Element) l.item(i);
			
			NodeList name = elmt.getElementsByTagName("longName");
			Element line = (Element) name.item(0);
			
			if(line == null) { // there's no long name
				name = elmt.getElementsByTagName("shortName");
				line = (Element) name.item(0);
			}
			
			Node child = line.getFirstChild();
			CharacterData cd = (CharacterData) child;
			System.out.println("Route: " + cd.getData());
		}
	}
}
